package com.learnyou.server.xingzuo.biz.handle;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SignUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import com.learnyou.server.xingzuo.common.constants.AuthConstants;
import com.learnyou.server.xingzuo.common.util.AssertUtil;
import com.learnyou.server.xingzuo.common.util.ServletUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @author heweifeng
 * @Description:
 * @date 2022/12/17 11:19
 */
@Aspect
@Component
public class DeviceAuthInterceptor {


    @Pointcut(value = "@annotation(com.learnyou.server.xingzuo.biz.handle.annotation.DeviceAuth)")
    public void cutService() {
    }

    /**
     *
     * 取设备号第三位的字符之后字符串作为公钥
     * 客户端对设备编号签名得到签名串
     * 这里对客户端签名的字符串进行验签
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("cutService()")
    public Object preHandle(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request = ServletUtils.getRequest();
        String deviceNo = request.getHeader(AuthConstants.DEVICE_NO);
        String signData = request.getHeader(AuthConstants.SIGN_DATA);
        String secretKey = StrUtil.sub(deviceNo, 3, deviceNo.length());
        String base64Key = Base64.encode(secretKey);
        Sign sign = SecureUtil.sign(SignAlgorithm.MD5withRSA, base64Key, base64Key);
        AssertUtil.checkCondition(sign.verify(deviceNo.getBytes(StandardCharsets.UTF_8), signData.getBytes(StandardCharsets.UTF_8)),"接口未授权！");
        return point.proceed();
    }

}
